package com.example.tcpmaster;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.cz.basetool.ui_work.util.log.AndroidConsoleLogPrinter;
import com.example.tcpmaster.callback.AbsTcpActionCallBack;
import com.example.tcpmaster.callback.AbsTcpUICallBack;
import com.example.tcpmaster.interfaces.IRelease;

import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lianxiang on 2017/9/6.
 * 业务Socket主类，将UI隔离。
 */

public abstract class AbsTcpManager implements IRelease {
    private static final String TAG = "AbsTcpManager";
    private List<AbsTcpUICallBack> tcpUICallBacks;    //连接状态UI回调
    private List<AbsTcpActionCallBack> tcpActionCallBacks;  //连接状态动作回调
    private TcpClient mTcpClient;
    private TcpConnectOptions tcpConnectOptions;
    private Context context;
    private Handler mHandler = new Handler(Looper.getMainLooper());
    private SocketListener socketListener;
    private boolean autoReconnect = false;


    protected AbsTcpManager() {
        AndroidConsoleLogPrinter.d(TAG, "AbsTcpManager 实例化");
    }

    /**
     * 添加UI回调操作类
     *
     * @param absTcpUICallBack
     */
    public void addUICallBack(AbsTcpUICallBack absTcpUICallBack) {
        if (tcpUICallBacks == null) {
            tcpUICallBacks = new ArrayList<>();
        }
        if (absTcpUICallBack != null) {
            absTcpUICallBack.bindTcpClient(mTcpClient);
            tcpUICallBacks.add(absTcpUICallBack);
        }
    }

    /**
     * 添加动作回调操作类
     *
     * @param absTcpActionCallBack
     */
    public void addActionCallBack(AbsTcpActionCallBack absTcpActionCallBack) {
        if (tcpActionCallBacks == null) {
            tcpActionCallBacks = new ArrayList<>();
        }

        if (absTcpActionCallBack != null) {
            if (socketListener != null) {
                absTcpActionCallBack.setSocketListener(socketListener);
            }
            tcpActionCallBacks.add(absTcpActionCallBack);
        }
    }

    public void setSocketListener(SocketListener socketListener) {
        this.socketListener = socketListener;
        if (tcpActionCallBacks == null || tcpActionCallBacks.size() == 0) {
            return;
        }
        for (AbsTcpActionCallBack tcpActionCallBack : tcpActionCallBacks) {
            if (tcpActionCallBack != null) {
                tcpActionCallBack.setSocketListener(socketListener);
            }
        }
    }

    public void init(Context context, TcpConnectOptions tcpConnectOptions) {
        this.context = context;
        if (tcpConnectOptions == null) {
            throw new RuntimeException("tcpConnectOptions == null,ip地址和端口号没有配置！");
        }
        this.tcpConnectOptions = tcpConnectOptions;

        mTcpClient = new TcpClient(tcpConnectOptions) {

            @Override
            public AbsSocketTransceiver getSocketTransceiver(TcpClient tcpClient, Socket socket) {
                return AbsTcpManager.this.getSocketTransceiver(tcpClient, socket);       //注意名字是一样的，小心栈溢出。
            }

            @Override
            public void onConnectted() {
                Log.d(TAG, "onConnectted: ");
                if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

                } else {
                    for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                        if (tcpUICallBack != null) {
                            tcpUICallBack.onConnectted();
                        }
                    }
                }


                if (tcpActionCallBacks == null || tcpActionCallBacks.size() == 0) {

                } else {
                    for (AbsTcpActionCallBack tcpActionCallBack : tcpActionCallBacks) {
                        if (tcpActionCallBack != null) {
                            //TODO 考虑后期可以加入优先级来控制动作回调的先后顺序
                            tcpActionCallBack.onConnectted();
                        }
                    }
                }

            }

            @Override
            public void onConnectFailed(int code, String message) {
                Log.e(TAG, "onConnectFailed: " + ",code = " + code + ",message = " + message);
                switch (code) {
                    case TcpSocketCode.SOCKET_FAILED:
                    case TcpSocketCode.SOCKET_TIMEOUT:
                        if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

                        } else {
                            for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                                if (tcpUICallBack != null) {
                                    tcpUICallBack.onConnectFailed(code, message);
                                }
                            }
                        }

                        if (tcpActionCallBacks == null || tcpActionCallBacks.size() == 0) {

                        } else {
                            for (AbsTcpActionCallBack tcpActionCallBack : tcpActionCallBacks) {
                                if (tcpActionCallBack != null) {
                                    tcpActionCallBack.onConnectFailed(code, message);
                                }
                            }
                        }
                        if (autoReconnect) {
                            reconnect();
                        }
                        break;
                }
            }

            @Override
            public void onReceive(String s) {
                Log.d(TAG, "onReceive: " + s);
                if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {
                } else {
                    for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                        if (tcpUICallBack != null) {
                            tcpUICallBack.onReceive(s);
                        }
                    }
                }
                if (tcpActionCallBacks == null || tcpActionCallBacks.size() == 0) {

                } else {
                    for (AbsTcpActionCallBack tcpActionCallBack : tcpActionCallBacks) {
                        if (tcpActionCallBack != null) {
                            tcpActionCallBack.onReceive(s);
                        }
                    }
                }

            }

            @Override
            public void onDisconnect() {
                Log.e(TAG, "onDisconnect: ");
                if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

                } else {
                    for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                        if (tcpUICallBack != null) {
                            tcpUICallBack.onDisconnect();
                        }
                    }
                }

                if (tcpActionCallBacks == null || tcpActionCallBacks.size() == 0) {

                } else {
                    for (AbsTcpActionCallBack tcpActionCallBack : tcpActionCallBacks) {
                        if (tcpActionCallBack != null) {
                            tcpActionCallBack.onDisconnect();
                        }
                    }
                }
                reconnect();
            }

            @Override
            public void onConnecting() {
                Log.d(TAG, "onConnecting: ");
                if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

                } else {
                    for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                        if (tcpUICallBack != null) {
                            tcpUICallBack.onConnecting();
                        }
                    }
                }

                if (tcpActionCallBacks == null || tcpActionCallBacks.size() == 0) {

                } else {
                    for (AbsTcpActionCallBack tcpActionCallBack : tcpActionCallBacks) {
                        if (tcpActionCallBack != null) {
                            tcpActionCallBack.onConnecting();
                        }
                    }
                }

            }

            @Override
            public void onException(Exception e) {
                Log.e(TAG, "onException: " + e.getMessage());
                if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

                } else {
                    for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                        if (tcpUICallBack != null) {
                            tcpUICallBack.onException(e);
                        }
                    }
                }

                if (tcpActionCallBacks == null || tcpActionCallBacks.size() == 0) {

                } else {
                    for (AbsTcpActionCallBack tcpActionCallBack : tcpActionCallBacks) {
                        if (tcpActionCallBack != null) {
                            tcpActionCallBack.onException(e);
                        }
                    }
                }


            }

            @Override
            public void onRequestTimeOut() {
                Log.e(TAG, "onRequestTimeOut: ");
                if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

                } else {
                    for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                        if (tcpUICallBack != null) {
                            tcpUICallBack.onRequestTimeOut();
                        }
                    }
                }

                if (tcpActionCallBacks == null || tcpActionCallBacks.size() == 0) {

                } else {
                    for (AbsTcpActionCallBack tcpActionCallBack : tcpActionCallBacks) {
                        if (tcpActionCallBack != null) {
                            tcpActionCallBack.onRequestTimeOut();
                        }
                    }
                }

            }
        };
    }

    public void release() {
        if (mTcpClient != null) {
            mTcpClient.disconnect();
            if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

            } else {
                for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                    if (tcpUICallBack != null) {
                        tcpUICallBack.release();
                    }
                }
            }

            if (tcpUICallBacks != null) {
                tcpUICallBacks.clear();
            }

            if (tcpActionCallBacks != null) {
                tcpActionCallBacks.clear();
            }
        }
    }

    public boolean sendMsg(byte[] byteArr) {
        if (mTcpClient != null && mTcpClient.isConnected()) {
            Log.d(TAG, "sendMsg1111: ");
            return mTcpClient.getTransceiver().send(byteArr);
        } else {
            Log.d(TAG, "sendMsg2222 : ");
            return false;
        }
    }


    public abstract boolean sendMsg(String str);


    public void startConnect() {
        mHandler.removeCallbacksAndMessages(null);          //清除已经发出去的重新连接请求
        connect();
    }

    /**
     * 重连
     */
    public void reconnect() {
        Log.d(TAG, "5s以后发起重连");
        if (mTcpClient.isConnected()) {
            mTcpClient.disconnect();
        }

        if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

        } else {
            for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                if (tcpUICallBack != null) {
                    tcpUICallBack.onReconnect();
                }
            }
        }


        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                connect();
            }
        }, tcpConnectOptions.getReConnectTime());
    }

    private void connect() {
        if (tcpUICallBacks == null || tcpUICallBacks.size() == 0) {

        } else {
            for (AbsTcpUICallBack tcpUICallBack : tcpUICallBacks) {
                if (tcpUICallBack != null) {
                    tcpUICallBack.onStartConnect();
                }
            }
        }


        mTcpClient.connect();
    }

    public boolean isConnected() {
        if (mTcpClient == null) return false;
        return mTcpClient.isConnected();
    }

    public abstract AbsSocketTransceiver getSocketTransceiver(TcpClient tcpClient, Socket socket);

    public void setAutoReconnect(boolean autoReconnect) {
        this.autoReconnect = autoReconnect;
    }


    /**
     * 连接服务器
     *
     * @param ip
     * @param port
     * @param tcpActionCallBack
     */
    public void connect(Context context, String ip, int port, AbsTcpActionCallBack tcpActionCallBack, AbsTcpUICallBack tcpUICallBack) {
        if (isConnected()) {
            release();
        }

        init(context,
                new TcpConnectOptions.Builder().hostIP(ip)
                        .port(port)
                        .create());
        addUICallBack(tcpUICallBack);
        addActionCallBack(tcpActionCallBack);
        startConnect();
    }

    /**
     * 连接服务器,默认使用TcpConfig配置的参数
     * @param tcpActionCallBack
     */
    public void connect(Context context,AbsTcpActionCallBack tcpActionCallBack, AbsTcpUICallBack tcpUICallBack) {
        if (isConnected()) {
            release();
        }

        init(context,
                new TcpConnectOptions.Builder().hostIP(TcpConfig.getInstance().getIp())
                        .port(TcpConfig.getInstance().getPort())
                        .create());
        addUICallBack(tcpUICallBack);
        addActionCallBack(tcpActionCallBack);
        startConnect();
    }

}
